#include "TinyTimer.h"


static tinytimer tinytimer_array[MAX_TIMER_COUNT];
tiny_timer_id tiny_timer_add(int interval, tinytimer_cb cb, void *userdata)
{
    int i = 0;
    for(i = 0 ; i < MAX_TIMER_COUNT; i++)
     {
        if(tinytimer_array[i].use_flag == 0)
           break;
     }
    if(i >= MAX_TIMER_COUNT)
      return -1;
    tinytimer_array[i].use_flag = 1;
    tinytimer_array[i].interval = interval;
    tinytimer_array[i].cb = cb;
    tinytimer_array[i].userdata = userdata;
    tinytimer_array[i].timeout = 0;
    return i;
}



int tiny_timer_del(tiny_timer_id timer_id)
{
    if(timer_id >= MAX_TIMER_COUNT || timer_id < 0)
        return -1;
    tinytimer_array[timer_id].use_flag = 0;
    return 0;
}



int tiny_timer_schedule(long long ticks)
{
    for(int i = 0 ; i < MAX_TIMER_COUNT; i++)
     {
         if(tinytimer_array[i].timeout == 0 && tinytimer_array[i].use_flag == 1)
         {
            tinytimer_array[i].timeout = ticks + tinytimer_array[i].interval;
         }
         else if(tinytimer_array[i].timeout <= ticks && tinytimer_array[i].use_flag == 1)
         {
            if(tinytimer_array[i].cb != NULL)
              tinytimer_array[i].cb(tinytimer_array[i].userdata);
            tinytimer_array[i].timeout = ticks + tinytimer_array[i].interval;
         }
     }

     return 0;

}